import React, { Component } from 'react'
import {
  Text,
  View,
  Alert,
  StyleSheet,
  Platform,
  PixelRatio,
  ScrollView,
  TextInput,
  TouchableOpacity,
  TouchableHighlight,
  Linking,
  TouchableWithoutFeedback,
} from 'react-native'
import Immutable from 'immutable'
import Icon from 'react-native-vector-icons/Ionicons'
import Icon2 from 'react-native-vector-icons/EvilIcons'
import ItemList from '../component/ItemList'
import RootView from '../component/RootView'
import Base from './Base'
import {
  NavigationActions,
  px2dp,
  getBorderWidth,
  isIos,
  imageServer,
} from '../utils'
import * as orderService from '../services/order'
import * as appService from '../services/app'

const borderWidth = getBorderWidth()

export class Button extends Component {
  render() {
    let color = '#999'
    if (this.props.color) {
      color = this.props.color
    }
    return (
      <TouchableOpacity
        onPress={() => this.props.onPress()}
        style={[styles.button, { borderColor: color }]}
      >
        <Text style={{ fontSize: 12, color }}>{this.props.children}</Text>
      </TouchableOpacity>
    )
  }
}

class OrderDetail extends Base {
  constructor(props) {
    super(props)
    this.state = {
      order: Immutable.Map(),
      items: Immutable.List(),
    }
  }
  static navigationOptions = {
    title: '订单明细',
    headerBackTitle: null,
    headerTitleStyle: {
      alignSelf: 'center',
    },
    headerStyle: {
      backgroundColor: 'white',
      borderBottomWidth: 0,
      shadowColor: 'transparent',
      elevation: 1,
    },
    headerRight: <View />,
  }

  loadData(orderId) {
    this.setState({ fetching: true })
    orderService
      .detail({ orderId })
      .then(data => {
        appService
          .config({})
          .then(config => {
            this.setState({
              fetching: false,
              csh: config.csh,
              order: Immutable.fromJS(data.order),
              items: Immutable.fromJS(data.items),
            })
          })
          .catch(e => {
            this.checkError(e)
          })
      })
      .catch(e => {
        this.checkError(e)
      })
  }
  orderCancel() {
    this.setState({ fetching: true })
    const { order } = this.state
    const orderId = order.get('id')
    orderService
      .cancel({ orderId })
      .then(data => {
        // 更新订单列表状态
        const { key } = this.props.navigation.state.params
        this.setParams(key, { reload: 1 })
        this.loadData(orderId)
      })
      .catch(e => {
        this.checkError(e)
      })
  }
  onOrderCancel() {
    Alert.alert(
      '确定取消订单？',
      null,
      [
        { text: '取消', style: 'cancel' },
        { text: '确定', onPress: () => this.orderCancel() },
      ],
      { cancelable: true }
    )
  }
  onAction(screenName) {
    const { key } = this.props.navigation.state
    const { order } = this.state
    const orderId = order.get('id')
    this.goto(screenName, { key, orderId })
  }
  openTel = () => {
    const { csh } = this.state

    if (!csh) {
      return
    }
    const url = `tel:${csh}`
    this.linkTo(url)
  }
  linkTo = url => {
    Linking.canOpenURL(url)
      .then(supported => {
        if (!supported) {
        } else {
          return Linking.openURL(url)
        }
      })
      .catch(err => console.error('An error occurred', err))
  }

  renderState(state, payType) {
    if (state == 1000 && payType != 0) {
      return <Text style={{ color: '#e23f3c' }}>待付款</Text>
    } else if (state == 1100 || (state == 1000 && payType == 0)) {
      return <Text>配送中</Text>
    } else if (state == 1110 || state == 1010) {
      return <Text>配送中</Text>
    } else if (state >= 2000) {
      return <Text>已完成</Text>
    } else if (state >= -2000 && state <= -1000) {
      return <Text>已取消</Text>
    }
  }
  renderPayType(payType){
    if(payType<0){
      return <Text>未选择</Text>
    }
    if(payType==0){
      return <Text>现金支付</Text>
    }
    if(payType==1){
      return <Text>支付宝</Text>
    }
    if(payType==2){
      return <Text>微信支付</Text>
    }
  }
  renderAction(state, payType) {
    if (state == 1000 && payType != 0) {
      return (
        <View style={styles.bar}>
          <View style={{ flex: 1 }}>
            <Text />
            <Text />
          </View>
          <View
            style={{
              flex: 1,
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'flex-end',
            }}
          >
            <Button onPress={() => this.onOrderCancel()}>取消订单</Button>
            {payType != 0 ? (
              <Button color="#e23f3c" onPress={() => this.onAction('Payment')}>
                支付订单
              </Button>
            ) : null}
          </View>
        </View>
      )
    }
    if (state >= 2000 && state < 2001) {
      return (
        <View style={styles.bar}>
          <View style={{ flex: 1 }}>
            <Text />
            <Text />
          </View>
          <View
            style={{
              flex: 1,
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'flex-end',
            }}
          >
            <Button onPress={() => this.onAction('Comment')}>评价</Button>
          </View>
        </View>
      )
    }
    return null
  }
  componentDidMount() {
    const { orderId } = this.props.navigation.state.params
    this.loadData(orderId)
  }

  render() {
    const { fetching, order, items } = this.state
    const address = order.get('village') + order.get('address')
    const state = order.get('state')
    const payType = order.get('payType')
    return (
      <RootView fetching={fetching} style={styles.container}>
        <ScrollView style={{ flex: 1 }}>
          <View style={[styles.item, { marginTop: 10 }]}>
            <View style={{ flex: 1, justifyContent: 'center' }}>
              <Text>
                订单号：<Text>{order.get('id')}</Text>
              </Text>
            </View>
            <View
              style={{
                width: 80,
                justifyContent: 'center',
                alignItems: 'flex-end',
              }}
            >
              {this.renderState(state, payType)}
            </View>

          </View>
          {payType<0?null:
           <View
              style={[
                styles.item,
                { paddingVertical: 8 },
              ]}
            >
              <View style={{ flex: 1, justifyContent: 'center' }}>
                <Text>支付方式</Text>
              </View>

              <View
                style={{
                  width: 80,
                  justifyContent: 'center',
                  alignItems: 'flex-end',
                }}
              >
                 <Text>{this.renderPayType(payType)}</Text>
              </View>
            </View>
          }
          <TouchableWithoutFeedback onPress={() => this.openTel()}>
            <View
              style={[
                styles.item,
                { borderBottomWidth: 0, paddingVertical: 8 },
              ]}
            >
              <View style={{ flex: 1, justifyContent: 'center' }}>
                <Text>联系客服</Text>
              </View>

              <View
                style={{
                  width: 80,
                  justifyContent: 'center',
                  alignItems: 'flex-end',
                }}
              >
                <Icon2 name="chevron-right" size={28} />
              </View>
            </View>
          </TouchableWithoutFeedback>
          <View style={[styles.item, { marginTop: 10 }]}>
            <View style={{ width: 20 }}>
              <Icon
                name="ios-pin-outline"
                style={{ color: '#666' }}
                size={18}
              />
            </View>
            <View style={{ flex: 1 }}>
              <View style={{ flexDirection: 'row' }}>
                <Text style={{ marginRight: 10 }}>{order.get('name')}</Text>
                <Text>{order.get('phone')}</Text>
              </View>
              <View>
                <Text style={{ color: '#999', marginTop: 5 }}>{address}</Text>
              </View>
            </View>
          </View>
          <View style={[styles.item, { marginTop: 10 }]}>
            <Text>商品清单</Text>
          </View>
          <ItemList data={items} />
          <View style={[styles.item2, { marginTop: 10 }]}>
            <View style={{ flex: 1, justifyContent: 'center' }}>
              <Text>商品总额</Text>
            </View>
            <View
              style={{
                width: 80,
                justifyContent: 'center',
                alignItems: 'flex-end',
              }}
            >
              <Text style={{ color: '#e23f3c' }}>￥{order.get('price')}</Text>
            </View>
          </View>
          <View style={[styles.item2]}>
            <View style={{ flex: 1, justifyContent: 'center' }}>
              <Text>+运费</Text>
            </View>
            <View
              style={{
                width: 80,
                justifyContent: 'center',
                alignItems: 'flex-end',
              }}
            >
              <Text style={{ color: '#e23f3c' }}>
                ￥{order.get('shipPrice')}
              </Text>
            </View>
          </View>
          <View style={[styles.item2]}>
            <View style={{ flex: 1, justifyContent: 'center' }}>
              <Text>-优惠</Text>
            </View>
            <View
              style={{
                width: 80,
                justifyContent: 'center',
                alignItems: 'flex-end',
              }}
            >
              <Text style={{ color: '#e23f3c' }}>￥{order.get('discount')}</Text>
            </View>
          </View>
          <View style={styles.total}>
            <View style={{ justifyContent: 'center', alignItems: 'flex-end' }}>
              <Text>
                合计：<Text style={{ color: '#e23f3c' }}>
                  ￥{order.get('totalPrice')}
                </Text>
              </Text>
            </View>
            <Text style={{ color: '#999', fontSize: 12, marginTop: 5 }}>
              下单时间：{order.get('createdAt')}
            </Text>
          </View>
        </ScrollView>
        {this.renderAction(state, payType)}
      </RootView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  item: {
    flexDirection: 'row',
    backgroundColor: 'white',
    borderColor: '#f0f0f0',
    borderBottomWidth: borderWidth,
    paddingHorizontal: 16,
    paddingVertical: 8,
  },
  item2: {
    flexDirection: 'row',
    backgroundColor: 'white',
    paddingHorizontal: 16,
    paddingVertical: 8,
  },
  total: {
    backgroundColor: 'white',
    borderColor: '#f0f0f0',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderTopWidth: borderWidth,
    justifyContent: 'center',
    alignItems: 'flex-end',
  },
  bar: {
    height: 48,
    paddingHorizontal: 16,
    flexDirection: 'row',
    backgroundColor: '#f9f9f9',
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    justifyContent: 'center',
    alignItems: 'center',

    borderRadius: isIos() ? 3 : 0,
    width: 70,
    height: 26,
    marginLeft: 8,
    borderWidth,
  },
})

export default OrderDetail
